package com.horizon.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author horizon
 */
public class ClientFactory {


    /**
     * @param connectionString
     * @return
     */
    public static CuratorFramework createSimple(String connectionString) {
        //重试策略：第一次重试等待1s,第二次重试等待2s,第三次重试等待4s
        //第一个参数：等待时间的基础单位，秒
        //第二个参数：最大重试次数
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        //简单获取CuratorFramework：
        //第一个参数:zk的连接地址
        //第二个参数:重试策略
        return CuratorFrameworkFactory.newClient(connectionString, exponentialBackoffRetry);
    }

    /**
     * @param connectionString
     * @param retryPolicy
     * @param connectionTimeoutMs
     * @param sessionTimeoutMs
     * @return
     */
    public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy,
                                                     int connectionTimeoutMs, int sessionTimeoutMs) {
        //builder模式创建curatorFramework
        return CuratorFrameworkFactory.builder().connectString(connectionString).retryPolicy(retryPolicy).connectionTimeoutMs(connectionTimeoutMs).sessionTimeoutMs(sessionTimeoutMs).build();
    }
}
